<template>
	<el-form ref="loginAccountRef" :model="formData" :rules="formRules" class="login-content-form">
		<el-form-item prop="loginName">
			<el-input type="text" :placeholder="$t('message.account.accountPlaceholder1')" prefix-icon="el-icon-user"
				v-model="formData.loginName" clearable autocomplete="off">
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input :type="isShowPassword ? 'text' : 'password'"
				:placeholder="$t('message.account.accountPlaceholder2')" prefix-icon="el-icon-lock"
				@keyup.enter.native="onSignIn" 
				v-model="formData.password" autocomplete="off">
				<template #suffix>
					<i class="iconfont el-input__icon login-content-password"
						:class="isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="isShowPassword = !isShowPassword">
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item v-if="kaptchaEnable" prop="verifyCode">
			<el-row :gutter="15">
				<el-col :span="16">
					<el-input type="text" maxlength="4" :placeholder="$t('message.account.accountPlaceholder3')" @keyup.enter.native="onSignIn"
						prefix-icon="el-icon-position" v-model="formData.verifyCode" clearable autocomplete="off">
					</el-input>
				</el-col>
				<el-col :span="8">
					<div class="login-content-code">
						<el-image :src="kaptchaUrl" @click="onKaptchaClick"></el-image>
					</div>
				</el-col>
			</el-row>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" class="login-content-submit" round @click="onSignIn" :loading="loading.signIn">
				<span>{{ $t('message.account.accountBtnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts">
import { toRefs, ref, reactive, defineComponent, computed, getCurrentInstance, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useStore } from '/@/store/index';
import { Local, Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { signIn, kaptchaVerify, getLoginUserInfo, getLoginUserAuthPage, getLoginUserAuthBtn } from '/@/api/login/index';
import { SM } from '/@/utils/sm';
export default defineComponent({
	name: 'login/account',
	setup() {
		const loginAccountRef = ref();
		const { t } = useI18n();
		const { proxy } = getCurrentInstance() as any;
		const store = useStore();
		const route = useRoute();
		const router = useRouter();
		const state = reactive({
			isShowPassword: false,
			kaptchaEnable: true,
			kaptchaUrl: '',
			formData: {
				loginName: '',
				password: '',
				verifyKey: '',
				verifyCode: '',
			},
			loading: {
				signIn: false,
			},
			formRules : {
				loginName: {required: true, message: '登录账号不能为空', trigger: 'blur' },
				password: { required: true, message: '登录密码不能为空', trigger: 'blur' },
				verifyCode: { required: true, message: '验证码不能为空', trigger: 'blur' },
			}
		});
		// 时间获取
		const currentTime = computed(() => {
			return formatAxis(new Date());
		});
		// 登录
		const onSignIn = () => {
			loginAccountRef.value.validate(valid => {
				if(valid){
					state.loading.signIn = true;
					const publicKey = Local.get('publicKey');
					let loginName = SM.sm2Encrypt(state.formData.loginName, publicKey);
					let password = SM.sm2Encrypt(state.formData.password, publicKey);
					let params = {
						loginName: loginName, 
						password: password, 
						verifyKey: state.formData.verifyKey, 
						verifyCode: state.formData.verifyCode,
					};
					signIn(params).then(async res => {
						// 关闭 loading
						state.loading.signIn = false;
						if(res.code == 0){
							// 存储 token 到浏览器缓存
							Session.set('token', res.data.accessToken);
							
							const info = await getLoginUserInfo();
							const page = await getLoginUserAuthPage();
							const butn = await getLoginUserAuthBtn();
							
							const userInfo = info.code == 0 ? info.data : {};
							userInfo.avatar = userInfo.avatar ? userInfo.avatar : '/images/profile.png';
							userInfo.authPageList = page.code == 0 ? page.data : [];
							userInfo.authBtnList = butn.code == 0? butn.data : [];
							
							// 存储用户信息到浏览器缓存
							Session.set('userInfo', userInfo);
							// 1、请注意执行顺序(存储用户信息到vuex)
							store.dispatch('userInfos/setUserInfos', userInfo);
		
							initControlRoutes();
						}else{
							//登录失败重置表单
							state.formData.verifyCode = null;
							loadKaptchaVerify();
						}
					},function(){
						// 关闭 loading
						state.loading.signIn = false;
					});
				}
			});
		};

		//初始化路由
		const initControlRoutes = async () => {
			if (!store.state.themeConfig.themeConfig.isRequestRoutes) {
				// 前端控制路由，2、请注意执行顺序
				await initFrontEndControlRoutes();
				signInSuccess();
			} else {
				// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
				// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
				await initBackEndControlRoutes();
				// 执行完 initBackEndControlRoutes，再执行 signInSuccess
				signInSuccess();
			}
		};
		// 登录成功后的跳转
		const signInSuccess = () => {
			// 初始化登录成功时间问候语
			let currentTimeInfo = currentTime.value;
			// 登录成功，跳到转首页
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
			if (route.query?.redirect) {
				router.push({
					path: route.query?.redirect,
					query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
				});
			} else {
				router.push('/');
			}
			// 登录成功提示
			setTimeout(() => {
				const signInText = t('message.signInText');
				ElMessage.success(`${currentTimeInfo}，${signInText}`);
				// 修复防止退出登录再进入界面时，需要刷新样式才生效的问题，初始化布局样式等(登录的时候触发，目前方案)
				proxy.mittBus.emit('onSignInClick');
			}, 300);
		};
		// 加载验证码
		const loadKaptchaVerify = () => {
			state.formData.verifyKey = new Date().getTime();
			kaptchaVerify({verifyKey: state.formData.verifyKey}).then((res) => {
				if(res && res.size > 0){
					const blob = new Blob([res]);
					var url = window.URL.createObjectURL(blob);
					state.kaptchaEnable = true;
					state.kaptchaUrl = url;
				}else{
					state.kaptchaEnable = false;
				}
			});
		}
		// 点击验证码
		const onKaptchaClick = () => {
			loadKaptchaVerify();
		}
		onMounted(() => {
			loadKaptchaVerify();
		});
		return {
			loginAccountRef,
			currentTime,
			onSignIn,
			onKaptchaClick,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	.login-content-password {
		display: inline-block;
		width: 25px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-code {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
}
</style>